package com.exwave.socialgame.amycontroller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.exwave.socialgame.myutils.ParamsException;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@ApiIgnore
@RestController
public class TestController {
    private String secret = "a1g2y47dg3dj59fjhhsd7cnewy73j";
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");


    @GetMapping("/test")
    @ApiOperation(value = "测试连接")
    public String testPage() {
        return "There is nothing !";
    }

    @GetMapping("UUID")
    @ApiOperation(value = "获取一个用户唯一识别码")
    public String uuid() {
        return UUID.randomUUID().toString();
    }

    @PostMapping("/createToken")
    @ApiOperation(value = "创建一个testToken，时效30s")
    //@ApiImplicitParam(name = "token", value = "Token", required = true, dataTypeClass = String.class, paramType = "header")
    public String createToken() {
        //生成token
        String token = JWT.create().withExpiresAt(new Date(System.currentTimeMillis() + 30 * 1000)) //30s过期
                .withAudience(secret)
                .sign(Algorithm.HMAC256(secret));
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ParamsException("Token验证失败 401");
        }
        return token;
    }

    @PostMapping("/varToken")
    @ApiOperation(value = "验证token有效性")
    @ApiImplicitParam(name = "token", value = "Token", required = true, dataTypeClass = String.class, paramType = "query")
    public boolean varToken(String token) {

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(secret)).build();
        try {
            verifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new ParamsException("Token验证失败 401");
        }
        return true;
    }
}
